#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" By Martin Senande-Rivera
	For Spatial and temporal expansion of global wildland fire activity in response to climate change """

import os
import glob, sys
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import xarray as xr
import datetime as dt 

ruta_in='./GFED4/DATA/'
ruta_out='./GFED4/'

gfeds=sorted(glob.glob(ruta_in+'GFED4.0_MQ_*.hdf'))
start_date = dt.datetime.strptime('1996-01', '%Y-%m')
dates = pd.date_range(start_date, periods=len(gfeds), freq='m')

lons = np.linspace(-179.875,179.875,1440)
lats = np.linspace(-89.875,89.875,720)
BA = xr.DataArray(np.zeros([len(gfeds),720, 1440]), 
	dims=['time','lat', 'lon'], 
	coords={'time':dates, 'lat': lats, 'lon': lons},
	name='BurnedArea')

x = [False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]
for i in range(len(gfeds)):
	ds_ba = xr.open_dataset(gfeds[i])
	per = ds_ba.LandCoverDist.values[x,:,:].sum(axis=0)/100.
	per[per>1.]=1.
	BA.values[i,:,:] = ds_ba.BurnedArea.values[::-1,:]*per[::-1,:]

BA_years = BA.groupby('time.year').sum(dim='time')
BA_monthly = BA.groupby('time.month').mean(dim='time')
BA_annual = BA.groupby('time.year').sum(dim='time').mean(dim='year')

BA.to_netcdf(ruta_out+'GFED4_BA_months.nc')
BA_years.to_netcdf(ruta_out+'GFED4_BA_years.nc')
BA_monthly.to_netcdf(ruta_out+'GFED4_BA_m_mean.nc')
BA_annual.to_netcdf(ruta_out+'GFED4_BA_a_mean.nc')
